import random

from django.shortcuts import render

# Create your views here.


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from celery_tasks.sms import tasks as sms_tasks
from . import constants


class SMSCodeView(GenericAPIView):
    """短信验证码"""

    def get(self, request, mobile):
        """创建短信验证码"""
        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 保存短信验证码和发送记录
        redis_conn = get_redis_connection("verify_codes")
        # redis管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 管道通知redis执行命令
        pl.execute()

        # 使用celery发送短信验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        sms_tasks.send_sms_code.delay(mobile, sms_code, expires)

        return Response({"message": "OK"})

